// 根路径
axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net';

// 获取元素
const tb = document.querySelector('#tb');
const form = document.querySelector('#bookForm');
const btns = document.querySelector('#btnSec');
const renderBooks = async () => {
  try {
    const { data: res } = await axios.get('/api/getbooks');
    const { data } = res;
    console.log(res);
    const html = data
      .map((item) => {
        return `<tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id="${item.id}">删除</a></td>
    </tr>`;
      })
      .join('');
    tb.innerHTML = html;
  } catch (error) {
    console.log(error);
  }
};

// 页面加载渲染
renderBooks();

// 添加功能
form.addEventListener('submit', async function (e) {
  e.preventDefault();

  const data = serialize(form, { hash: true });

  const { data: res } = await axios.post('/api/addbook', data);

  if (res.status !== 201) return alert(res.msg);
  alert(res.msg);
  this.reset();
  renderBooks();
});

// 删除功能
tb.addEventListener('click', async function (e) {
  if (e.target.tagName === 'A') {
    // 获取自定义id
    let id = e.target.dataset.id;

    // 发删除请求
    const { data: res } = axios.get('/api/delbool?id' + id);

    renderBooks();
  }
});

